package com.msa.msaportal.webservice;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ResourceBundle;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.Base64;
import org.json.JSONException;
import org.json.JSONObject;

import com.msa.msaportal.common.web.ConstantUntil;
import com.msa.msaportal.entity.PortalheaderEntity;
import com.msa.msaportal.entity.Template;
import com.msa.msaportal.service.IHeaderService;
import com.msa.msaportal.service.ITemplateService;

public class HeaderServicesImpl implements HeaderServices {
	@Resource(name = "headerService")
	private IHeaderService headerService;
	@Resource(name = "templateManager")
	private ITemplateService templateManager;

	String success = "{'result':'0','info':'操作成功!'}";
	String fail = "{'result':'1','info':'操作失败!'}";
	String exception = "{'result':'2','info':'接口异常!'}";
	
	// 获得项目路径
	String fileSaveDataPathHeaderImage = ResourceBundle.getBundle("commonurl").getString("fileSaveDataPathHeaderImage");
	String fileSaveDrivePath = getClass().getResource("/").getFile().toString().replace("build/classes/", "")+"WebContent/";
	@Override
	public String addHeader(String data) throws Exception {

		try {
			PortalheaderEntity header = new PortalheaderEntity();
			JSONObject dataJson = new JSONObject(data);

			header.setIspublic(Integer.valueOf(dataJson.getString("public")));
			header.setOrgname(dataJson.getString("orgName"));
			header.setCreateusername(dataJson.getString("author"));
			header.setUpdateusername(dataJson.getString("alter"));
			header.setCreatetime(dataJson.getString("createTime"));
			header.setUpdatetime(dataJson.getString("updateTime"));
			String orgId = dataJson.getString("orgId");
			if (orgId.trim().equals("")) {
				return "{'result':'4','info':'orgId不能为空!'}";
			}
			header.setOrgid(orgId);
			header.setCreateuserid(dataJson.getString("authorId"));
			header.setUpdateuserid(dataJson.getString("alterId"));
			// 获得headerId
			String HsourceId = dataJson.getString("HeaderId");
			header.setHsource_id(HsourceId);
			// 模板id
			String templateId = dataJson.getString("templateOrStyleId");

			// 上传图片
			String imageFile = dataJson.getString("imageFile");
			String imageName = dataJson.getString("imageName");
			String NameSuffix = imageName.substring(imageName.lastIndexOf("."),
					imageName.length());

			if (imageFile != null && !imageFile.equals("")) {

				byte[] fileByte = Base64.decodeBase64(imageFile);
				// 查看父目录是否存在
				// String path1 = filePath + "/file/headerimage/";
				File file = new File(fileSaveDrivePath + fileSaveDataPathHeaderImage);
				if (!file.exists()) {
					file.mkdirs();
				}
				File backupfile=new File(ConstantUntil.BACKUPIMGE_URL);
				if (!backupfile.exists()) {
					backupfile.mkdirs();
				}
				DateFormat MONTH_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss");
				int randomnum = (int) (Math.random()*9000+1000);
				String datetime = MONTH_FORMAT.format(new Date())+randomnum;
				String path = fileSaveDrivePath + fileSaveDataPathHeaderImage +"/"+ datetime + NameSuffix;
				try {
					FileOutputStream fileOutputStream = new FileOutputStream(path);
					FileOutputStream backupfileOut = new FileOutputStream(ConstantUntil.BACKUPIMGE_URL+datetime + NameSuffix);
					fileOutputStream.write(fileByte);
					backupfileOut.write(fileByte);
					fileOutputStream.flush();
					backupfileOut.flush();
					fileOutputStream.close();
					backupfileOut.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					String fail = "{'result':'1','info':'文件上传失败!'}";
					return fail;
				}
				// 保存路径
				String path2 = fileSaveDataPathHeaderImage + "/" + datetime
						+ NameSuffix;
				header.setLogo_url(path2);
				header.setImageUrl(path2);
			}

			try {
				// 添加头
				System.out.println("header"+header);
				headerService.addHeader(header);
				// 获得header
				PortalheaderEntity headerEntity = headerService.find(HsourceId);
				// 通过模板Id查询模板并保存header到模板
				Template template = templateManager.findByTresourse_Id(templateId);
				template.setHeader(headerEntity);
				templateManager.addHeadOrFoontToTmp(template);
			} catch (Exception e) {
				e.printStackTrace();
				return fail;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return exception;
		}
		return success;
	}

	public String changeHeader(String data) throws JSONException {
		try {
			JSONObject dataJson = new JSONObject(data);
			System.out.println("dataJson"+dataJson);
			String createuserid = dataJson.getString("createuserid");
			String isOpen =dataJson.has("public")?dataJson.getString("public"):"";
			String orgId =dataJson.has("orgId")?dataJson.getString("orgId"):"";
			String createtime = dataJson.getString("createtime");
			String createusername = dataJson.getString("createusername");
			// 模板id
			String headerId = dataJson.getString("headerId");
			// 上传图片
			String imageFile = dataJson.getString("imageFile");
			String imageName = dataJson.getString("imageName");

			String NameSuffix = imageName.substring(imageName.lastIndexOf("."),
					imageName.length());

			// 查询headerEntity对象
			PortalheaderEntity headerEntity = headerService.find(headerId);
			if(headerEntity==null){
				headerEntity=new PortalheaderEntity();
				headerEntity.setHsource_id(headerId);
				System.out.println("header"+headerEntity);
				headerService.addHeader(headerEntity);
				// 获得header
				PortalheaderEntity headerEntity2 = headerService.find(headerId);
				// 通过模板Id查询模板并保存header到模板
				Template template = templateManager.findByTresourse_Id(headerId);
				template.setHeader(headerEntity2);
				templateManager.addHeadOrFoontToTmp(template);
			}
			System.out.println(headerEntity);
			// 添加字段参数
			System.out.println(createuserid+createtime+createusername);
			headerEntity.setCreateuserid(createuserid);
			headerEntity.setCreatetime(createtime);
			headerEntity.setCreateusername(createusername);
			headerEntity.setIspublic(Integer.parseInt(isOpen));
			headerEntity.setOrgid(orgId);
			// 获得文件路径删除文件
			String logo_url = headerEntity.getLogo_url();
			String logo_url2 = fileSaveDrivePath + logo_url;
			File file = new File(logo_url2);
			if (file.isFile() && file.exists()) {
				file.delete();
			}
			File backupfile = new File(ConstantUntil.BACKUP_PATH+logo_url);
			if (backupfile.isFile() && backupfile.exists()) {
				backupfile.delete();
			}
			// 文件上传
			if (imageFile != null && !imageFile.equals("")) {

				byte[] fileByte = Base64.decodeBase64(imageFile);
				// 查看父目录是否存在
				// String path1 = filePath + "/file/headerimage";
				File file1 = new File(fileSaveDrivePath
						+ fileSaveDataPathHeaderImage);
				if (!file1.exists()) {
					file1.mkdirs();
				}
				File backupImg=new File(ConstantUntil.BACKUPIMGE_URL);
				if (!backupImg.exists()) {
					backupImg.mkdirs();
				}
				DateFormat MONTH_FORMAT = new SimpleDateFormat(
						"yyyyMMddddHHmmss");
				int randomnum = (int) (Math.random()*9000+1000);
				String datetime = MONTH_FORMAT.format(new Date())+randomnum;
				String path = fileSaveDrivePath + fileSaveDataPathHeaderImage + "/" + datetime + NameSuffix;

				// 保存路径
				String path3 = fileSaveDataPathHeaderImage + "/" + datetime + NameSuffix;
				headerEntity.setImageUrl(path3);
				headerEntity.setLogo_url(path3);

				try {
					FileOutputStream fileOutputStream = new FileOutputStream(path);
					FileOutputStream backupfileOut = new FileOutputStream(ConstantUntil.BACKUPIMGE_URL+datetime + NameSuffix);
					fileOutputStream.write(fileByte);
					backupfileOut.write(fileByte);
					fileOutputStream.flush();
					backupfileOut.flush();
					fileOutputStream.close();
					backupfileOut.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					String fail = "{'result':'1','info':'文件上传失败!'}";
					return fail;
				}
			}
			try {
				// 更新headerEntity对象
				headerService.updater(headerEntity);
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				return fail;
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return exception;
		}
		return success;
	}
}
